

require("../model/studentsModel");
const mongoose = require('mongoose');
const jwt = require("jsonwebtoken");

async function login(req, res, next) {
    let users = await mongoose.model('studentsModel').find({});
    console.log(users);
    let { user, pass } = req.body;
    //判断是否登录成功:filter
    let result = users.filter(u => u.phone == user && u.password == pass);
    console.log(result[0]);
    if (result.length > 0) {
        //登录成功
         //生成token返回到前端
        const token = jwt.sign(
        { user: result[0] }, //  用户信息
        "user", // 密钥，任意字符串,主要是为了后面的服务器解密进行鉴权
        { expiresIn: 10 } //设置token有效期,纯数字以秒为单位， 支持字符串 "10 days"  "8h"
      );
        res.send({
            message:'登陆成功',
            code:200,
            token: "Bearer " + token,
            user:result[0]//返回用户数据
        });
    } else {
        res.send({message:'登陆失败',code:-1});
    }
  
}

async  function register(req, res, next) {
    // 拿到数据库里的所有用户数据
    let users = await mongoose.model('studentsModel').find({});
    let { phone, password, name} = req.body;
    //注册
    //先判断是否有该用户，如果有则失败，没有则追加
    let result = users.some((u) => u.phone ==phone);
    if (result) {
        //已存在
        res.send({ message: '该用户已存在', code: -1 });
    } else {
        let users  = await mongoose.model('studentsModel').create(req.body);
        console.log(users);
        // users.push({...req.body });
        res.send({ message: '注册成功', code: 200 });
    }

    res.send({message:'注册测试通过',code:200});
}


module.exports = {
    login,register
}